// ==UserScript==
// @name         Iwara使用Aria2下载原视频
// @namespace    http://tampermonkey.net/
// @version      0.0.1-2024-11-14
// @description  在视频播放页添加“Aria2”按钮，点击调用Aria2下载原视频
// @match        https://www.iwara.tv/video/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=iwara.tv
// @grant        GM_xmlhttpRequest
// @author       AgMonk
// @homepage     https://gitee.com/AgMonk/tampermonkey-script
// @downloadURL https://gitee.com/AgMonk/tampermonkey-script/raw/master/iwara/iwara-aria2-download.user.js
// @updateURL https://gitee.com/AgMonk/tampermonkey-script/raw/master/iwara/iwara-aria2-download.user.js

// ==/UserScript==

(function () {
    'use strict';

    let id = 0;

    // 运行参数，可以 localStorage.setItem 方法填入对应KEY修改

    // rpcUrl的KEY和默认值
    const RPC_URL_KEY = "RPC_URL";
    const DEFAULT_RPC_URL = "http://localhost:6800/jsonrpc";

    // 代理服务器IP端口的KEY和默认值
    const HTTPS_PROXY_KEY = "HTTPS_PROXY";
    const DEFAULT_HTTPS_PROXY = "127.0.0.1:7890";

    // 下载目录的KEY和默认值
    const DOWNLOAD_DIR_KEY = "DOWNLOAD_DIR";
    const DEFAULT_DOWNLOAD_DIR = "d:/iwara";

    // 从localStorage中获取运行参数，如果为空则取默认值
    const getValue = (key, defaultValue) => {
        const value = localStorage.getItem(key)
        return value ? value : defaultValue
    }
    // 添加下载任务
    const addUri = function (src) {
        // 今天日期
        const date = new Date().toLocaleDateString().replace(/\//g, '_')
        const filename = new URL(src).searchParams.get("download").replaceAll(/[<>:"/|?*\x00-\x1F]/g, "")
        console.log(`下载: ${filename}`)
        return GM_xmlhttpRequest({
            method: 'POST',
            url: getValue(RPC_URL_KEY, DEFAULT_RPC_URL),
            headers: {
                "Content-Type": "application/json"
            },
            data: JSON.stringify({
                "id": id++,
                "jsonrpc": "2.0",
                "method": "aria2.addUri",
                "params": [
                    [src],
                    {
                        "dir": `${getValue(DOWNLOAD_DIR_KEY, DEFAULT_DOWNLOAD_DIR)}/${date}`,
                        "https-proxy": getValue(HTTPS_PROXY_KEY, DEFAULT_HTTPS_PROXY),
                        "out": filename,
                    }
                ]
            }),
            onload: function (res) {
                let response = JSON.parse(res.response)
                console.log(response)
                alert("任务已添加")
            },
        });
    }


    // 按钮栏
    const actionButtonDiv = document.getElementsByClassName('page-video__actions')

    const interval = setInterval(() => {
        if (actionButtonDiv) {
            const downloadButtons = actionButtonDiv[0].getElementsByClassName('downloadButton')
            if (downloadButtons && downloadButtons[0]) {
                downloadButtons[0].click()

                const links = actionButtonDiv[0].getElementsByTagName('a')
                console.log(links)
                if (links && links[0]) {
                    // 原视频地址
                    const url = links[0].href;
                    // 生成按钮
                    const button = document.createElement('button');
                    button.className = 'button shareButton button--primary button--solid'
                    button.type = 'button'
                    button.style.marginLeft = '10px'
                    button.innerText = 'Aria2'
                    button.onclick = () => {
                        addUri(url)
                    }
                    actionButtonDiv[0].appendChild(button)


                    setTimeout(() => downloadButtons[0].click(), 200)
                    clearInterval(interval)
                }
            }
        }

    }, 2000)


    // Your code here...
})();
